import pako from 'pako';

/**
 * 格式化日期
 * @param value 日期时间
 * @param fmt 格式
 */
export const crtTimeFtt = (value, fmt) => {
  fmt = fmt || 'YYYY-MM-DD';
  if (value){
    if (typeof value === 'string'){
      // value = value.replace(/-/g,'/');
      let date = new Date(value);
      return formatDate(date,fmt);
    }
    if (typeof value === 'number'){
      let date = new Date(value);
      return formatDate(date,fmt);
    }
    if (typeof value === 'object'){
      return formatDate(value,fmt)
    }
  }
  return formatDate(new Date(),fmt);
};
/**
 * 格式化日期时间格式
 * @param {Date} date 日期时间对象
 * @param {String} fmt 格式
 */
export const formatDate = (date, fmt) => {
  const o = {
    'M+': date.getMonth() + 1,  //月份
    'D+': date.getDate(),   //日期
    'H+': date.getHours(),  //时
    'm+': date.getMinutes(),  //分
    's+': date.getSeconds(),  //秒
    'q+': Math.floor((date.getMonth() + 3) / 3),  // 季度
    'S': date.getMilliseconds(),    // 毫秒
  }

  if (/(Y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  for (let k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, o[k].toString().length === 1 ? '0' + o[k] : o[k])
    }
  }
  return fmt;

}
export const getPrevDay = (date) =>{
  let today,oneDay = 1000 * 60 * 60 * 24;
  if (date) today = new Date(date);
  else today = new Date();
  let toDay = today.getTime();
  let prevDay = toDay - oneDay;
  let newDay = today.setTime(prevDay);
  return new Date(newDay);
}
export const getNextDay = (date) =>{
  let today,oneDay = 1000 * 60 * 60 * 24;
  if (date) today = new Date(date);
  else today = new Date();
  let toDay = today.getTime();
  let prevDay = toDay + oneDay;
  let newDay = today.setTime(prevDay);
  return new Date(newDay);
}
/**
 * 获取某个月第一天
 * @param {number|string} year
 * @param {number|string} month 1-12
 */
export const getMonthFirstDate = (year, month) => {
  if(year === undefined || month === undefined) {
    let today = new Date()
    year = today.getFullYear()
    month = today.getMonth() + 1
  }
  return new Date(year, month - 1, 1)
}
/**
 * 获取某个月最后一天
 * @param {number|string} year
 * @param {number|string} month 1-12
 */
export const getMonthLastDate = (year, month) => {
  if(year === undefined || month === undefined) {
    let today = new Date()
    year = today.getFullYear()
    month = today.getMonth() + 1
  }
  return new Date(year, month, 0)
}
/**
 * 获取某日所在周的第一天
 * @param date
 * @return {Date}
 */
export const getWeekFirstDate = (date) =>{
  let today;
  if (date) today = new Date(date);
  else today = new Date();
  const year = today.getFullYear(),
    month = today.getMonth(),
    day = today.getDate(),
    week = today.getDay();
  return new Date(year,month, day - week + 1)
}
/**
 * 获取某日所在周的最后一天
 * @param date
 * @return {Date}
 */
export const getWeekLastDate = (date) =>{
  let today;
  if (date) today = new Date(date);
  else today = new Date();
  const year = today.getFullYear(),
    month = today.getMonth(),
    day = today.getDate(),
    week = today.getDay();
  return new Date(year,month, day - week + 7)
}
/**
 * 获取某日所在季度的第一天
 * @param date
 * @return {Date}
 */
export const getQuarterFirstDate = (date) => {
  let today;
  if (date) today = new Date(date);
  else today = new Date();
  const year = today.getFullYear(),
    month = today.getMonth(),
    day = today.getDate(),
    week = today.getDay();
  let m = 0;
  if(month<3){//012
    m = 0
  }else if(2<month && month<6){//345
    m = 3
  }else if(5<month && month<8){//678
    m = 6
  }else if(month>8){ //9 10 11
    m = 9
  }
  return new Date(year,m, 1)
}
/**
 * 获取某日所在季度的最后一天
 * @param date
 * @return {Date}
 */
export const getQuarterLastDate = (date) => {
  let today;
  if (date) today = new Date(date);
  else today = new Date();
  const year = today.getFullYear(),
    month = today.getMonth(),
    day = today.getDate(),
    week = today.getDay();
  let m = 0;
  if(month<3){//012
    m = 3
  }else if(2<month && month<6){//345
    m = 6
  }else if(5<month && month<8){//678
    m = 9
  }else if(month>8){ //9 10 11
    m = 0
  }
  return new Date(year,m, 0)
}


/**
 * 下载文件
 * @param resBlob blob格式文件
 * @param fileName  下载文件名
 * @param target  当前页面下载，新窗口下载
 */
// export const downFile = (resBlob, fileName, fileType = '.xls',type = 'application/vnd.ms-excel;charset=utf-8', target = '_self') => {
export const downFile = (resBlob, fileName, target = '_self') => {

  if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    // 兼容IE/Edge
    window.navigator.msSaveOrOpenBlob(resBlob, fileName)
  } else {
    var url = window.URL.createObjectURL(resBlob);
    var a = document.createElement('a');
    a.href = url;
    a.target = target;
    a.style.display = 'none';
    a.setAttribute('download', fileName)
    document.body.appendChild(a);
    a.click()
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url)
  }
}
/**
 * 图片文件压缩
 * @param file
 * @description
 *  1、将文件转img对象
 *  2、获取文件宽高比例
 *  3、自定义等比例缩放宽高属性，这里我用的是固定800宽度，高度是等比例缩放
 *  4、canvas重新绘制图片
 *  5、canvas转二进制对象转文件对象，返回

 * @return {Promise<*>}
 */
export const imgCompress = async file => {
  const img = await file2Img(file);
  return new Promise((resolve,reject) => {
    const canvas = document.createElement('canvas'),
      context = canvas.getContext('2d');
    //  获取文件宽高比例
    const {width: originWidth, height: originHeight} = img;
    //  自定义等比例缩放宽高属性， 固定面积220000，宽度高度等比例缩放
    const scale = +(originWidth /originHeight).toFixed(2) //比例取小数点后两位
    const s = 220000,
      targetWidth = Math.round(Math.sqrt(scale * s)),
      targetHeight = Math.round(targetWidth / scale);

    canvas.width = targetWidth
    canvas.height = targetHeight
    context.clearRect(0, 0, targetWidth, targetHeight)
    // canvas重新绘制图片
    context.drawImage(img, 0, 0, targetWidth, targetHeight)

    // canvas转二进制对象转文件对象，返回
    const type = 'image/png'
    canvas.toBlob(blob => {
      const f = new File([blob], file.name, {
        type,
        lastModified: file.lastModified
      })
      resolve(f)
    }, type)

  })
}

/**
 * 图片file转化成img对象
 * @param file
 * @return {Promise<any>}
 */
export const  file2Img = (file) => {
  return new Promise((resolve,reject) => {
    const img = new Image(),
      reader = new FileReader();
    reader.onload = e => img.src = e.target.result;
    reader.onerror = e => reject(e);
    reader.readAsDataURL(file);
    img.onload = () => resolve(img);
    img.onerror = (e) => reject(e);
  })
}

/**
 * 复制
 * @param text
 */
export const copyText = (text) => {
  return new Promise(resolve => {
//创建input标签
    var input = document.createElement('input')
    //将input的值设置为需要复制的内容
    input.value = text;
    //添加input标签
    document.body.appendChild(input)
    //选中input标签
    input.select()
    //执行复制
    document.execCommand('copy')
    //移除input标签
    document.body.removeChild(input);

    resolve();
  })
}

/**
 * 字符串转base64
 * @param str
 * @return {string}
 */
export const str2Base64 = (str) => {
  return btoa(encodeURI(str));
}

/**
 * gzip解压
 * @param str 压缩字符串
 * @return {String} 字符串
 */
export const unzip = (str) => {
  var strData = atob(str);
  var charData = strData.split('').map(function(x){return x.charCodeAt(0);});
  var data= pako.ungzip(charData, { to: 'string' });
  return data
}

/**
 * 深拷贝
 * @param aObject
 * @return {*}
 */
export const deepClone = (aObject) => {
  if (!aObject) {
    return aObject;
  }
  var bObject, v, k;
  bObject = Array.isArray(aObject) ? [] : {};
  for (k in aObject) {
    v = aObject[k];
    bObject[k] = (typeof v === "object") ? deepClone(v) : v;
  }
  return bObject;
}
